<template>
  <div class="register-container">
    <div class="register-form">
      <h2>注册</h2>
      <!-- 全局错误提示 -->
      <el-alert
        v-if="globalError"
        type="error"
        :title="globalError"
        show-icon
        :closable="false"
        style="margin-bottom: 20px;"
      />
      <el-form :model="registerForm" :rules="rules" ref="registerFormRef">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="registerForm.username" placeholder="请输入用户名" prefix-icon="User" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="registerForm.email" placeholder="请输入邮箱地址" prefix-icon="Mail" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="registerForm.password" type="password" placeholder="请输入密码" prefix-icon="Lock" show-password />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="registerForm.confirmPassword" type="password" placeholder="请确认密码" prefix-icon="Lock" show-password />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleRegister" :loading="loading" style="width: 100%">注册</el-button>
        </el-form-item>
      </el-form>
      <div class="login-link">
        已有账号？<a href="/login">立即登录</a>
      </div>
    </div>
  </div>
</template>

<script>
import { authService } from '../services/authService';

export default {
  name: 'RegisterView',
  data() {
    return {
      registerForm: {
        username: '',
        email: '',
        password: '',
        confirmPassword: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '用户名长度必须在3-10个字符之间', trigger: 'blur' },
          { pattern: /^[a-zA-Z0-9_\u4e00-\u9fa5]+$/, message: '用户名只能包含字母、数字、下划线或中文', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请确认密码', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (value !== this.registerForm.password) {
                callback(new Error('两次输入的密码不一致'));
              } else {
                callback();
              }
            },
            trigger: 'blur'
          }
        ]
      },
      loading: false,
      globalError: ''
    };
  },
  methods: {
    async handleRegister() {
      // 清除之前的全局错误
      this.globalError = '';
      
      this.$refs.registerFormRef.validate(async (valid) => {
        if (valid) {
          this.loading = true;
          try {
            const userData = {
              username: this.registerForm.username,
              email: this.registerForm.email,
              password: this.registerForm.password,
              confirmPassword: this.registerForm.confirmPassword
            };
            
            console.log('提交注册数据:', userData);
            const response = await authService.register(userData);
            
            console.log('注册响应:', response);
            
            // 检查响应中是否有错误信息
            if (response && (response.error || !response.token)) {
              // 显示全局错误信息，避免在表单字段上显示相同的错误
              this.globalError = response.message || response.error?.message || '注册失败，请稍后重试';
            } else {
              // 注册成功
              this.$message.success('注册成功');
              this.$router.push('/');
            }
          } catch (error) {
            console.error('注册错误详情:', error);
            // 显示更详细的错误信息
            this.globalError = error.response?.data?.message || 
                               error.response?.data?.error || 
                               error.message || 
                               '注册失败，请稍后重试';
          } finally {
            this.loading = false;
          }
        }
      });
    }
  },
  // 如果已登录，直接跳转到首页
  beforeMount() {
    if (authService.isAuthenticated()) {
      this.$router.push('/');
    }
  }
};
</script>

<style scoped>
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f5f5f5;
}

.register-form {
  width: 400px;
  padding: 30px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.register-form h2 {
  text-align: center;
  margin-bottom: 30px;
  color: #303133;
}

.login-link {
  text-align: center;
  margin-top: 20px;
  color: #909399;
}

.login-link a {
  color: #409eff;
  text-decoration: none;
}

.login-link a:hover {
  text-decoration: underline;
}
</style>